package t327.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.domain.OrderDetail;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import t327.mapper.ContractOrderPayMapper;
import t327.mapper.PayOrderTableMapper;
import t327.pojo.OrderForm;
import t327.pojo.PayOrderTable;
import t327.pojo.ali.Configs;
import t327.pojo.ali.PayCall;
import t327.pojo.views.ContractOrderPayView;
import t327.service.iter.IContractOrderPayService;
import t327.util.AlipayUtil;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ContractOrderPayServiceImpl implements IContractOrderPayService {
    @Autowired
    private ContractOrderPayMapper contractOrderPayMapper;
    @Autowired
    private PayOrderTableMapper payOrderTableMapper;
    @Override
    public List<ContractOrderPayView> queryPay() {
        return contractOrderPayMapper.queryPay();
    }

    @Override
    public HashMap<String, String> payForPayCode(String contractNumber, String payCode, Long roleId, Long clientId) {
        HashMap<String, String> map = new HashMap<>();

        ContractOrderPayView contractOrderPayView = contractOrderPayMapper.queryByContractNumber(contractNumber);
        if(contractOrderPayView!=null) {
            BigDecimal orderMoney = contractOrderPayView.getOrderMoney();
            String contractNumber1 = contractOrderPayView.getContractNumber();
            //相关的本系统业务操作
            String outTradeNo = AlipayUtil.generateOutTradeNo();
            PayOrderTable payOrderTable = new PayOrderTable();
            payOrderTable
                    .setOrderAmount(orderMoney)
                    .setCreatedTime(new Date())
                    .setContractNumber(contractNumber1)
                    .setOutTradeNo(outTradeNo)
                    .setPayType(1L)
                    .setRoleId(roleId)
                    .setModeOfPayment(1L)
                    .setClientId(clientId);
            int addOrder =  payOrderTableMapper.addPayOrder(payOrderTable);
            if(addOrder!=1){

                map.put("code", "206");
                map.put("msg", "创建订单主表失败");
                return  map;
            }
            AlipayTradePayModel model = new AlipayTradePayModel();
            model.setTotalAmount(orderMoney.toString());
            model.setAuthCode(payCode);
            model.setScene("bar_code");
            model.setOutTradeNo(outTradeNo);
            model.setSubject("合同");
            AlipayTradePayResponse response = AlipayUtil.payForPayCode(model);

            if(response!=null){
                if(response.getCode().equals("10000")){
                    payOrderTable.setId(payOrderTable.getId());
                    payOrderTable.setPayType(2L);
                    payOrderTable.setUpdateTime(new Date());
                    int  updateById=  payOrderTableMapper.updatePayOrderTable(payOrderTable);
                    if(updateById!=1){
                        //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        map.put("code", "207");
                        map.put("msg", "缴费成功但是修改订单主表状态失败,请联系管理员");
                        return map;

                    }else{
                        map.put("code", "200");
                        map.put("msg", "缴费成功");
                        return map;
                    }
                }
                map.put("code", response.getSubCode());
                map.put("msg", response.getSubMsg());
            }else{
                map.put("code", "202");
                map.put("msg", "支付宝无法响应，请稍后再试");
            }

        }
        return map;
    }

    @Override
    public ContractOrderPayView queryByContractNumber(String contractNumber) {
        return contractOrderPayMapper.queryByContractNumber(contractNumber);
    }

    @Override
    public PayOrderTable findOrderById(String contractNumber) {

        return payOrderTableMapper.findOrderById(contractNumber);
    }

    @Override
    public HashMap refundForOrder(String outTradeNo) {
        HashMap<String, String> map = new HashMap<>();

        PayOrderTable payOrderTable= payOrderTableMapper.queryByoutTradeNo(outTradeNo);
        if(payOrderTable==null){
            map.put("code", "201");
            map.put("msg", "未查询到订单，请重新再试");
            return map;
        }

        if(payOrderTable.getPayType()!=2L){
            map.put("code", "202");
            map.put("msg", "该订单不支持退款");
            return map;
        }
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        model.setOutTradeNo(outTradeNo);
        model.setRefundAmount(payOrderTable.getOrderAmount().toString());
        AlipayTradeRefundResponse response = AlipayUtil.refundForOrder(model);
        if(response!=null){
            if(response.getCode().equals("10000")){
                payOrderTable.setPayType(3L);
                payOrderTable.setUpdateTime(new Date());
                int  updateById=  payOrderTableMapper.updatePayOrderTable(payOrderTable);
                if(updateById!=1){
                    //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    map.put("code", "207");
                    map.put("msg", "退费成功但是修改订单主表状态失败,请联系管理员");
                    return map;
                }else{
                    map.put("code", "200");
                    map.put("msg", "退费成功");
                    return map;
                }
            }
            map.put("code", response.getSubCode());
            map.put("msg", response.getSubMsg());
        }else{
            map.put("code", "202");
            map.put("msg", "支付宝无法响应，请稍后再试");

        }

        return map;
    }

    @Override
    public HashMap<String, String> confirmPay(String outTradeNo, Map<String, String> parameterMap) {

        HashMap<String, String> map = new HashMap<>();
        PayOrderTable payOrderTable = payOrderTableMapper.queryByoutTradeNo(outTradeNo);
        if(payOrderTable.getPayType()!=1L){
            map.put("code", "201");
            map.put("msg", "订单状态不对");
            return map;
        }

        boolean isOk =AlipayUtil.verify(parameterMap);
        if(isOk){
            payOrderTable.setPayType(2L);
            payOrderTable.setUpdateTime(new Date());
            payOrderTableMapper.updatePayOrderTable(payOrderTable);
            map.put("code", "200");
            map.put("msg", "确认付款成功");
            System.out.println("确认付款成功");
            return map;
        }else{
            map.put("code", "203");
            map.put("msg", "验签不通过");
            return map;
        }
    }

    @Override
    public Map<String, String> preCreate(String contractNumber, Long roleId, Long clientId) {
        HashMap<String, String> map = new HashMap<>();
        ContractOrderPayView contractOrderPayView = contractOrderPayMapper.queryByContractNumber(contractNumber);
        if(contractOrderPayView!=null) {
            HashMap<String, Object> createOrderResult = createPayOrder(contractNumber, roleId, clientId, contractOrderPayView);
            String code = (String)createOrderResult.get("code");
            String msg = (String)createOrderResult.get("msg");
            PayOrderTable payOrderTable = (PayOrderTable)createOrderResult.get("order");
            String outTradeNo = payOrderTable.getOutTradeNo();
            if(code==null||!code.equals("200")){
                map.put("code", code);
                map.put("msg", msg);
                return map;
            }
            AlipayTradePrecreateModel alipayTradePrecreateModel = new AlipayTradePrecreateModel();

            alipayTradePrecreateModel.setOutTradeNo(outTradeNo);

            alipayTradePrecreateModel.setTotalAmount(contractOrderPayView.getOrderMoney().toString());
            alipayTradePrecreateModel.setSubject(contractOrderPayView.getClientName());

            AlipayTradePrecreateResponse alipayTradePrecreateResponse = AlipayUtil.preCreate(alipayTradePrecreateModel);
            String qrCode = alipayTradePrecreateResponse.getQrCode();
            map.put("code", "200");
            map.put("msg", "生成订单成功");
            map.put("qrcode", qrCode);
            map.put("Id", payOrderTable.getId().toString());
            return map;
        } else{
            map.put("code", "203");
            map.put("msg", "未知产品");
            return map;
        }
    }
    private HashMap<String,Object> createPayOrder(String contractNumber, Long roleId, Long clientId,ContractOrderPayView contractOrderPayView){
        HashMap<String, Object> map = new HashMap<>();

        if (contractOrderPayView != null) {
            BigDecimal price1 = contractOrderPayView.getOrderMoney();
            //相关的本系统业务操作
            String outTradeNo = AlipayUtil.generateOutTradeNo();
            PayOrderTable payOrderTable = new PayOrderTable();
            BigDecimal orderMoney = contractOrderPayView.getOrderMoney();
            String contractNumber1 = contractOrderPayView.getContractNumber();
            //相关的本系统业务操作
            payOrderTable
                    .setOrderAmount(orderMoney)
                    .setCreatedTime(new Date())
                    .setContractNumber(contractNumber1)
                    .setOutTradeNo(outTradeNo)
                    .setPayType(1L)
                    .setRoleId(roleId)
                    .setModeOfPayment(1L)
                    .setClientId(clientId);
            int addOrder =  payOrderTableMapper.addPayOrder(payOrderTable);
            if (addOrder != 1) {
                map.put("code", "206");
                map.put("msg", "创建订单主表失败");
                return map;
            }
            map.put("code", "200");
            map.put("msg", "创建订单成功");
            map.put("order", payOrderTable);
            return map;
        }
        map.put("code", "207");
        map.put("msg", "产品找不到");
        return map;

    }

}
